const express = require('express');
const router = express.Router();
const User = require('../../models/user');

// 获取用户列表
router.get('/', async (req, res) => {
  try {
    const { page = 1, limit = 10, keyword = '' } = req.query;
    const skip = (page - 1) * limit;

    const query = {};
    if (keyword) {
      query.$or = [
        { username: new RegExp(keyword, 'i') },
        { email: new RegExp(keyword, 'i') }
      ];
    }

    const users = await User.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .select('-password')
      .sort({ createdAt: -1 });

    const total = await User.countDocuments(query);

    res.json({
      code: 0,
      data: {
        list: users,
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '获取用户列表失败',
      error: error.message
    });
  }
});

// 获取单个用户
router.get('/:id', async (req, res) => {
  try {
    const user = await User.findById(req.params.id).select('-password');
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    res.json({
      code: 0,
      data: user
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '获取用户信息失败',
      error: error.message
    });
  }
});

// 更新用户信息
router.put('/:id', async (req, res) => {
  try {
    const { username, email, role } = req.body;
    const user = await User.findByIdAndUpdate(
      req.params.id,
      { username, email, role },
      { new: true }
    ).select('-password');

    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }

    res.json({
      code: 0,
      data: user
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '更新用户信息失败',
      error: error.message
    });
  }
});

// 删除用户
router.delete('/:id', async (req, res) => {
  try {
    const user = await User.findByIdAndDelete(req.params.id);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    res.json({
      code: 0,
      message: '删除用户成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '删除用户失败',
      error: error.message
    });
  }
});

module.exports = router; 